var base_url = getApp().globalData.base_url
var app = getApp()
Page({
    data: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
    },

    onConfirm() {
        let userId = app.globalData.userId
        let oldPassword = this.data.oldPassword
        let newPassword = this.data.newPassword
        let confirmPassword = this.data.confirmPassword

        // 判断原密码格式是否正确
        if (oldPassword.length == 0 || !/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(oldPassword)) {
            wx.showModal({
                title: "错误",
                content: "原密码格式不正确"
            });
            return
        }

        // 判断新密码格式是否正确
        if (newPassword.length == 0 || !/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(newPassword)) {
            wx.showModal({
                title: "错误",
                content: "新密码格式不正确"
            });
            return
        }

        if (!(newPassword === confirmPassword)) {
            wx.showModal({
                title: "错误",
                content: "两次输入的密码不一致"
            });
            return
        }

        // 发送请求
        wx.request({
            url: base_url + '/users/password',
            method: 'PUT',
            header: {
                "content-type": 'application/x-www-form-urlencoded'
            },
            data: {
                userId: userId,
                oldPassword: oldPassword,
                newPassword: newPassword
            },
            success(res) {
                if (res.data.resultCode == 200) {
                    console.log(res.data.message)
                    wx.showToast({
                        title: '修改密码成功',
                        icon: 'success',
                        duration: 3000//持续的时间
                    })
                    // TODO 弹出修改成功提示，跳转回主页面
                    wx.navigateBack({
                        delta: 0,
                    })
                } else {
                    wx.showToast({
                        title: '原密码错误',
                        icon: 'error',
                        duration: 2500//持续的时间
                    })
                }
            }
        })
    },



    onOldInput(e) {
        this.setData({
            oldPassword: e.detail.value
        })
    },
    onNewInput(e) {
        this.setData({
            newPassword: e.detail.value
        })
    },
    onConConfirmInput(e) {
        this.setData({
            confirmPassword: e.detail.value
        })
    },
});
